import os.path
import random
import string
import time
from datetime import datetime, timezone
from turtle import pd

#openpyxl 是一个 Python 库，用于读取和写入 Excel 文件
import openpyxl
import pytz
from django.contrib.auth.hashers import check_password, make_password
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, ValidationError
from django.db import transaction, IntegrityError
from django_redis import get_redis_connection
from django_redis.serializers import pickle
from rest_framework import serializers, authentication, permissions

from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.exceptions import ParseError

# from StudentV4BE import settings
from StudentV4BE.settings import CACHE_MIDDLEWARE_KEY_PREFIX
from apps.accounts.models import CustomUser
#这里导入了名为 Student 的模型类，
# 模型类定义了数据库中表的结构和行为。
# 在 Django 中，通过导入模型类，可以进行数据库的增删改查操作，以及对数据库中数据的处理和管理。
from apps.rootone.models import Student, Rootone_if, Class, User, Course, CourseTeacherZj, CourseClassZj, \
    Other_teacher_class, Location

#JsonResponse 是 Django 提供的一个便捷的 HTTP 响应类，
# 用于返回 JSON 数据。在视图函数中，可以使用它将 JSON 格式的数据返回给客户端，通常用于 AJAX 请求或 API 接口。
from django.http import JsonResponse
import json

# 导入哈希
import uuid
import hashlib
# 导入setting

import os
from django.conf import settings

# Create your views here.
# 进行查询使用的是django的Q查询
from django.db.models import Q

# 定义一个全局的缓存版本变量，初始化为1
CACHE_VERSION = 1


#处理登录请求的导入
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from apps.teacherapp.models import Teacher, T_award, teacher_award_zj
from apps.studentapp.models import student_award_zj, S_award, SStudents
from .serializers import LoginSerializer
#
#处理注册请求的导入
from .serializers import RegisterSerializer

# 导入api保护标签
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes


# 导入redis缓存的标签
from django.views.decorators.cache import cache_page



from django.test.client import RequestFactory
from django.core.cache import cache
from django.views.decorators.cache import cache_page
from django.urls import reverse


#定义了一个名为 get_students 的函数，接收接收客户端发来的请求信息 request 对象作为参数，该对象包含了客户端发来的请求信息。
@api_view(['GET'])
# @cache_page(60 * 5)  # 缓存5分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def get_students(request):
    """获取所有学生信息"""
    try:
        data = request.query_params
        user_id = data.get('rootid')

        if not user_id:
            return Response({'code': 0, 'message': '缺少管理员认证编号'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 0, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        # 查询所有学生，并且包括班级名称
        obj_students = SStudents.objects.all().select_related('of_class').values(
            'student_id', 'name', 'rname', 'sex', 'level', 'birthday', 'phone',
            'origin', 'mailbox', 'by_school', 'school_encode', 'hire', 'college',
            'of_class__class_name', 'f_name', 'f_phone', 'm_name', 'm_phone', 'address'
        )

        # 将 QuerySet 转换为列表，并处理 of_class__class_name 字段
        students_list = list(obj_students)
        for student in students_list:
            #
            student['of_class'] = student.pop('of_class__class_name', None)
        # 返回 JSON 格式的响应
        return JsonResponse({'code': 1, 'data': students_list}, safe=False)

    except Exception as e:
        return JsonResponse({'code': 0, 'message': f'捕获学生信息出现异常: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
# @cache_page(60 * 10)  # 缓存10分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def query_students(request):
    """查询学生信息"""
    # 对于外键class的处理是查询班级名称，通过班级名称进行匹配
    try:
        data = request.query_params
        user_id = data.get('rootid')
        print(user_id)
        if not user_id:
            return Response({'code': 0, 'message': '缺少管理员认证编号'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 0, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)
        try:
            # 使用ORM获取满足条件的学生信息，并把对象转为字典格式
            obj_students = SStudents.objects.filter(Q(student_id__icontains=data.get('inputstr')) |
                                                    Q(rname__icontains=data.get('inputstr')) |
                                                    Q(sex__icontains=data.get('inputstr')) |
                                                    Q(phone__icontains=data.get('inputstr')) |
                                                    Q(mailbox__icontains=data.get('inputstr')) |
                                                    Q(birthday__icontains=data.get('inputstr')) |
                                                    Q(origin__icontains=data.get('inputstr')) |
                                                    Q(by_school__icontains=data.get('inputstr')) |
                                                    Q(school_encode__icontains=data.get('inputstr')) |
                                                    Q(hire__icontains=data.get('inputstr')) |
                                                    Q(college__icontains=data.get('inputstr')) |
                                                    Q(of_class__class_name__icontains=data.get('inputstr')) |
                                                    Q(f_name__icontains=data.get('inputstr')) |
                                                    Q(f_phone__icontains=data.get('inputstr')) |
                                                    Q(m_name__icontains=data.get('inputstr')) |
                                                    Q(m_phone__icontains=data.get('inputstr')) |
                                                    Q(address__icontains=data.get('inputstr'))).values()
            #把外层容器转为List
            student = list(obj_students)
            #返回
            return JsonResponse({'code': 1, 'data': student})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': "查询学生信息出现异常"+str(e)})
    except Exception as e:
        # 捕获所有其他异常并返回服务器错误响应
        print(f"Unexpected error: {e}")  # 调试信息
        return Response({'code': 0, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



@api_view(['GET'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def is_exsits_sno(request):
    """判断学号是否存在"""
    #接收传递过来的学号
    data = request.query_params

    try:
        obj_students = SStudents.objects.filter(student_id=data.get('student_id'))
        if obj_students.count() == 0:
            #设置返回的参数，1表示请求成功且不存在该学号
            return JsonResponse({'code': 1, 'exists': False})
        else:
            return JsonResponse({'code': 1, 'exists': True})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "校验学号失败，具体原因: "+ str(e)})

@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def add_student(request):
    """添加学生到数据库"""
    try:
        # 获取前端传递过来的数据
        data = request.data
        print(data)
        # 校验 rootid 是否存在且有效
        rootid = data.get('rootid')
        if not rootid:
            return Response({'code': 0, 'message': '缺少rootid'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=rootid)
        except Rootone_if.DoesNotExist:
            return Response({'code': 0, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        # 定义必填字段列表
        required_fields = ['student_id', 'rname', 'sex', 'phone', 'origin']

        # 验证必填字段是否存在并且非空
        for field in required_fields:
            if field not in data or not data[field].strip():
                return Response({'code': 0, 'message': f'缺少必填字段或为空: {field}'},
                                status=status.HTTP_400_BAD_REQUEST)

        # 处理可选的日期字段，将空字符串转换为 None
        def parse_date(date_str):
            if date_str and date_str.strip():
                try:
                    return datetime.strptime(date_str, '%Y-%m-%d').date()
                except ValueError:
                    raise ParseError(detail='日期格式不正确')
            return None

        birthday = parse_date(data.get('birthday'))
        hire = parse_date(data.get('hire'))

        # 使用事务保证原子性
        with transaction.atomic():
            # 实例化班级对象
            try:
                class_object = Class.objects.get(class_name=data.get('of_class').strip())
            except Class.DoesNotExist:
                return Response({'code': 2, 'message': '班级名称错误，无此班级'}, status=status.HTTP_404_NOT_FOUND)

            # 创建 SStudents 对象并赋值
            obj_student = SStudents(
                student_id=data.get('student_id'),
                rname=data.get('rname'),
                sex=data.get('sex'),
                phone=data.get('phone'),
                origin=data.get('origin'),
                birthday=birthday,
                mailbox=data.get('email'),
                by_school=data.get('by_school'),
                school_encode=data.get('school_encode'),
                hire=hire,
                f_name=data.get('f_name'),
                f_phone=data.get('f_phone'),
                m_name=data.get('m_name'),
                m_phone=data.get('m_phone'),
                address=data.get('address'),
                college=data.get('college'),
                of_class=class_object
            )

            # 执行保存操作
            obj_student.save()


            # 保存学生信息后为其创建账号
            student_obj = SStudents.objects.filter(student_id=data.get('student_id')).first()

            # 创建账号
            CustomUser.objects.create(
                identifier=data.get('student_id'),
                user_type='student',
                password=make_password(str(data.get('student_id'))),
                student_info=student_obj
            )

            # 使用ORM获取所有学生信息，并把对象转为字典格式
            obj_students = SStudents.objects.all().values()
            # 把外层容器转为List
            student = list(obj_students)
            # 返回
            return JsonResponse({'code': 1, 'data': student})

            # 返回成功信息
            return Response({'code': 1, 'message': '学生信息添加成功'}, status=status.HTTP_200_OK)

    except ParseError as pe:

        return Response({'code': 0, 'message': str(pe.detail)}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:

        return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 处理可选的日期字段，将空字符串转换为 None
def parse_date(date_str):
    if date_str and date_str.strip():
        try:
            from datetime import datetime  # 在函数内部导入以确保局部作用域
            parsed_date = datetime.strptime(date_str, '%Y-%m-%d').date()
            return parsed_date
        except ValueError as ve:
            raise ValidationError({'message': '日期格式不正确', 'details': str(ve)})
    return None

@api_view(['PUT'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def update_student(request):
    """修改学生到数据库"""
    try:
        data = request.data

        # 校验 rootid 是否存在且有效
        user_id = data.get('rootid')
        if not user_id:
            return Response({'code': 0, 'message': '缺少管理员认证编号'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 0, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        # 查找要修改的学生信息
        student_id = data.get('student_id')
        if not student_id:
            return Response({'code': 0, 'message': '缺少必填字段: student_id'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            obj_student = SStudents.objects.get(student_id=student_id)  # 使用 student_id 字段查找学生
        except SStudents.DoesNotExist:
            return Response({'code': 0, 'message': '找不到指定的学生'}, status=status.HTTP_404_NOT_FOUND)

            # 处理可选的日期字段，将空字符串转换为 None
        birthday = parse_date(data.get('birthday')) if data.get('birthday') else None
        hire = parse_date(data.get('hire')) if data.get('hire') else None

        # 使用事务保证原子性
        with transaction.atomic():
            # 如果提供了班级名称，则更新班级外键
            class_name = data.get('of_class')
            if class_name:
                class_object = Class.objects.filter(class_name=class_name.strip()).first()
                if not class_object:
                    return Response({'code': 2, 'message': '班级名称错误，无此班级'}, status=status.HTTP_404_NOT_FOUND)
                obj_student.of_class = class_object


            # 构建 Student 对象的参数字典，并过滤掉值为 None 或空字符串的键值对
            student_data = {
                key: (parse_date(value) if key in ['birthday', 'hire'] else value)
                for key, value in data.items()
                if hasattr(SStudents, key) and (value is not None and value != '') and key != 'of_class' and key != 'rootid'
            }


            # 更新 Student 对象的属性
            for key, value in student_data.items():
                setattr(obj_student, key, value)
            # 执行保存操作
            try:
                obj_student.save()
            except IntegrityError as e:
                return Response({'code': 0, 'message': f'保存时出现完整性错误: {str(e)}'}, status=status.HTTP_400_BAD_REQUEST)
            # 使用ORM获取所有学生信息，并把对象转为字典格式
            obj_students = SStudents.objects.all().values()
            # 把外层容器转为List
            student = list(obj_students)
            # 返回
            return JsonResponse({'code': 1, 'data': student})
            # 返回成功信息
            return Response({'code': 1, 'message': '学生信息更新成功'}, status=status.HTTP_200_OK)

    except ValidationError as ve:

        return Response({'code': 0, 'message': str(ve)}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:


        return Response({'code': 0, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['DELETE'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def delete_student(request):
    """删除一条学生数据"""
    try:

        data = request.data
        # 查找到要修改的学生信息
        # 校验 rootid 是否存在且有效
        user_id = data.get('rootid')
        if not user_id:
            return Response({'code': 0, 'message': '缺少管理员认证编号'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 0, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        obj_student = SStudents.objects.get(student_id=data.get('student_id'))
        # 执行删除
        obj_student.delete()

        # 使用ORM获取所有学生信息，并把对象转为字典格式
        obj_students = SStudents.objects.all().values()
        # 把外层容器转为List
        student = list(obj_students)
        # 返回
        return JsonResponse({'code': 1, 'data': student})

    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "删除学生信息写入数据库出现异常：具体原因-" + str(e)})

@api_view(['DELETE'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def delete_students(request):
    """批量删除学生信息"""
    try:
        data = request.data
        # 校验 rootid 是否存在且有效
        user_id = data.get('rootid')
        if not user_id:
            return Response({'code': 0, 'message': '缺少管理员认证编号'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 0, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)
        # 遍历传递的集合，并确保 student 是一个列表
        students_to_delete = data.get('student', [])
        if not isinstance(students_to_delete, list):
            return Response({'code': 0, 'message': '无效的学生学号列表'}, status=status.HTTP_400_BAD_REQUEST)
        # 使用事务保证原子性
        with transaction.atomic():
            # 执行删除操作
            SStudents.objects.filter(student_id__in=[t['student_id'] for t in students_to_delete]).delete()

            # 使用ORM获取所有教师信息，并把对象转为字典格式
            obj_students = SStudents.objects.all().values()
            # 把外层容器转为List
            student = list(obj_students)
            # 返回
            return JsonResponse({'code': 1, 'data': student})


            return Response({'code': 1, 'message': '批量删除成功'}, status=status.HTTP_200_OK)
    except Exception as e:
        # 捕获所有其他异常并返回服务器错误响应
        print(f"Unexpected error: {e}")  # 调试信息
        return Response({'code': 0, 'msg': "批量删除学生信息出现异常：具体原因-" + str(e)},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)


def upload(request):
    """接收上传的文件"""
    # 接收上传的文件
    rev_file = request.FILES.get('avatar')
    # 判断是否有文件
    if not rev_file:
        return JsonResponse({'code': 0, 'msg': '图片不存在'})

    # 获得一个唯一的名字： uuid + hash
    new_name = get_random_str()
    # 准备写入的URL
    file_path = os.path.join(settings.MEDIA_ROOT, new_name + os.path.splitext(rev_file.name)[0])
    # 开始写入到本地磁盘
    try:
        with open(file_path,'wb') as f:
            # 多次写入
            for i in rev_file.chunks():
                # 写入
                f.write(i)
            f.close()
        # 返回
        return JsonResponse({'code': 1, 'name': new_name + os.path.splitext(rev_file.name)[0]})

    except Exception as e:
        return JsonResponse({'code': 0, 'msg': str(e)})


def get_random_str():
    # 获取uuid的随机数
    uuid_val = uuid.uuid4()
    # 获取uuid的随机数字符串
    uuid_str = str(uuid_val).encode('utf-8')
    # 获取md5实例
    md5 = hashlib.md5()
    # 拿取uuid的md5摘要
    md5.update(uuid_str)
    # 返回固定长度的字符串
    return md5.hexdigest()


# 从Excel批量导入学生信息
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def import_student_excel(request):
    """从Excel批量导入学生信息"""
    # 1. 接收Excel文件并存储到Media文件夹
    rev_file = request.FILES.get('excel')
    if not rev_file:
        return JsonResponse({'code': 0, 'msg': 'Excel文件不存在'})

    # 获得一个唯一的名字并添加扩展名
    new_name = get_random_str() + os.path.splitext(rev_file.name)[1]
    file_path = os.path.join(settings.MEDIA_ROOT, new_name)

    # 保存文件
    try:
        with open(file_path, 'wb') as f:
            for chunk in rev_file.chunks():
                f.write(chunk)
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': f'文件保存失败: {str(e)}'})

    # 2. 读取存储在Media文件夹的数据
    try:
        ex_students = read_excel_dict(file_path)
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': f'读取Excel文件失败: {str(e)}'})

    # 3. 把读取的数据存储在数据库
    success = 0
    error = 0
    error_snos = []

    for one_student in ex_students:
        try:
            # 在学生基础信息表创建信息
            SStudents.objects.create(
                student_id=one_student['student_id'],
                rname=one_student['really_name'],
                sex=one_student['sex'],
                phone=one_student['mobile'],
                origin=one_student['origin']
            )

            student_obj = SStudents.objects.filter(student_id=one_student['student_id']).first()

            # 创建账号
            CustomUser.objects.create(
                identifier=one_student['student_id'],
                user_type='student',
                password=make_password(str(one_student['student_id'])),
                student_info=student_obj
            )

            success += 1
        except Exception as e:
            error += 1
            error_snos.append(one_student['student_id'])
            print(f'学生导入失败: {one_student["student_id"]}, 错误: {str(e)}')

    # 4. 返回导入信息
    obj_students = SStudents.objects.all().values()
    students = list(obj_students)
    return JsonResponse({'code': 1, 'success': success, 'error': error, 'errors': error_snos, 'data': students})

# 读取excel内容（辅助从Excel批量导入学生信息）
def read_excel_dict(path: str):
    """读取excel数据，存储为字典"""
    workbook = openpyxl.load_workbook(path)
    sheet = workbook.active  # 获取活动的sheet，假设文件中只有一个sheet
    students = []
    keys = ['student_id', 'really_name', 'sex',  'mobile', 'origin']

    for row in sheet.iter_rows(min_row=2, values_only=True):  # 假设数据从第二行开始
        temp_dict = {keys[index]: value for index, value in enumerate(row)}
        students.append(temp_dict)

    return students

# 导出学生数据到Excel
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
@api_view(['GET'])
def export_student_excel(request):
    """导出数据到Excel"""
    # 获取所有的学生信息
    obj_students = SStudents.objects.all().values()
    # 转为List
    students = list(obj_students)
    # 准备名称
    excel_name = get_random_str() + ".xlsx"

    # 准备写入的路径
    path = os.path.join(settings.MEDIA_ROOT, excel_name)

    # 写入数据到Excel文件
    write_to_excel(students, path)

    #返回

    return JsonResponse({'code': 1, 'name': excel_name})

# 把数据写入到Excel（辅助导出学生数据到Excel）
def write_to_excel(data: list, path: str):
    """把数据写入到Excel"""
    # 实例化一个workbook
    workbook = openpyxl.Workbook()

    # 激活一个sheet
    sheet = workbook.active
    # 为sheet命名
    sheet.title = 'student'

    # 准备keys
    keys = data[0].keys()

    # 准备写入数据
    for index, item in enumerate(data):
        for k, v in enumerate(keys):
            sheet.cell(row=index + 1, column=k + 1, value=str(item[v]))

#     写入到文件
    workbook.save(path)



# 从Excel批量导入教师信息
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def import_teacher_excel(request):
    """从Excel批量导入教师信息"""
    # 1. 接收Excel文件并存储到Media文件夹
    rev_file = request.FILES.get('excel')
    if not rev_file:
        return JsonResponse({'code': 0, 'msg': 'Excel文件不存在'})

    # 获得一个唯一的名字并添加扩展名
    new_name = get_random_str() + os.path.splitext(rev_file.name)[1]
    file_path = os.path.join(settings.MEDIA_ROOT, new_name)

    # 保存文件
    try:
        with open(file_path, 'wb') as f:
            for chunk in rev_file.chunks():
                f.write(chunk)
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': f'文件保存失败: {str(e)}'})

    # 2. 读取存储在Media文件夹的数据
    try:
        ex_teachers = read_excel_dict(file_path)
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': f'读取Excel文件失败: {str(e)}'})

    # 3. 把读取的数据存储在数据库
    success = 0
    error = 0
    error_snos = []

    for one_teacher in ex_teachers:
        try:
            # 在学生基础信息表创建信息
            Teacher.objects.create(
                sid=one_teacher['teacher_id'],
                rname=one_teacher['really_name'],
                sex=one_teacher['sex'],
                phone=one_teacher['mobile'],
                origin=one_teacher['origin']
            )

            teacher_obj = Teacher.objects.filter(sid=one_teacher['student_id']).first()

            # 创建账号
            CustomUser.objects.create(
                identifier=one_teacher['teacher_id'],
                user_type='teacher',
                password=make_password(str(one_teacher['teacher_id'])),
                student_info=teacher_obj
            )

            success += 1
        except Exception as e:
            error += 1
            error_snos.append(one_teacher['teacher_id'])
            print(f'教师导入失败: {one_teacher["teacher_id"]}, 错误: {str(e)}')

    # 4. 返回导入信息
    obj_teachers = Teacher.objects.all().values()
    teachers = list(obj_teachers)
    return JsonResponse({'code': 1, 'success': success, 'error': error, 'errors': error_snos, 'data': teachers})

# 读取excel内容（辅助从Excel批量导入教师信息）
def read_teacher_excel_dict(path: str):
    """读取excel数据，存储为字典"""
    workbook = openpyxl.load_workbook(path)
    sheet = workbook.active  # 获取活动的sheet，假设文件中只有一个sheet
    students = []
    keys = ['teacher_id', 'really_name', 'sex',  'mobile', 'origin']

    for row in sheet.iter_rows(min_row=2, values_only=True):  # 假设数据从第二行开始
        temp_dict = {keys[index]: value for index, value in enumerate(row)}
        students.append(temp_dict)

    return students

# 导出教师数据到Excel
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
@api_view(['GET'])
def export_teacher_excel(request):
    """导出数据到Excel"""
    # 获取所有的教师信息
    obj_teachers = Teacher.objects.all().values()
    # 转为List
    teachers = list(obj_teachers)
    # 准备名称
    excel_name = get_random_str() + ".xlsx"

    # 准备写入的路径
    path = os.path.join(settings.MEDIA_ROOT, excel_name)

    # 写入数据到Excel文件
    write_to_excel(teachers, path)

    #返回

    return JsonResponse({'code': 1, 'name': excel_name})

# 把数据写入到Excel（辅助导出教师数据到Excel）
def write_teacher_to_excel(data: list, path: str):
    """把数据写入到Excel"""
    # 实例化一个workbook
    workbook = openpyxl.Workbook()

    # 激活一个sheet
    sheet = workbook.active
    # 为sheet命名
    sheet.title = 'teacher'

    # 准备keys
    keys = data[0].keys()

    # 准备写入数据
    for index, item in enumerate(data):
        for k, v in enumerate(keys):
            sheet.cell(row=index + 1, column=k + 1, value=str(item[v]))

#     写入到文件
    workbook.save(path)










def all_rootone_if(request):
    if request.method == 'GET':
        try:
            all_root_if = Rootone_if.objects.all().values()
            list_all_if = list(all_root_if)
            print(list_all_if)
            return JsonResponse({'code': 1, 'data': list_all_if}, status=200)
        except Exception as e:
            print(f'捕获管理员全部信息失败，原因是{e}')
    else:
        print('传递的参数格式有误')

#处理登录请求的view
class loginView(APIView):

    def post(self, request, *args, **kwargs):
        # 获取 cookie
        auto_cookie = request.COOKIES.get('auto_cookie')
        rememberme = request.data.get('rememberMe')

        if auto_cookie:
            if auto_cookie == "some_secure_value":
                return Response({'message': '访问成功'}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '令牌信息错误！'}, status=status.HTTP_401_UNAUTHORIZED)

        # 创建 LoginSerializer 实例
        serializer = LoginSerializer(data=request.data)

        if serializer.is_valid():
            user = serializer.validated_data["user"]
            response = Response({
                "userid": user.rroot_id,
                "message": "登录成功"
            }, status=status.HTTP_200_OK)

            cookie_max_age = 2 * 60 * 60 if rememberme else None
            response.set_cookie(
                key="auto_cookie",
                value="some_secure_value",
                max_age=cookie_max_age,
                secure=False,
                samesite='None',
                httponly=True,
            )
            return response
        else:
            # 如果验证失败，返回错误信息
            return Response({
                "errors": serializer.errors,
                "message": "登录失败，数据无效"
            }, status=status.HTTP_400_BAD_REQUEST)



#处理注册请求的view
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
class RegisterView(APIView):
    def post(self, request, *args, **kwargs):
        # 创建变量保存RegisterSerializer类的一个实例
        serializer = RegisterSerializer(data=request.data)
        if serializer.is_valid():
            # serializer.is_valid()：这是 Django REST Framework 中的一个方法，
            # 用于检查传入的数据是否符合序列化器 LoginSerializer 中定义的规则和字段。
            serializer.save()
            return Response({
                "userid": serializer.data["userid"],
                "username": serializer.data["username"],
                "message": "注册成功"
            }, status=status.HTTP_201_CREATED)
        #如果数据验证失败，serializer.errors 将包含详细的错误信息，例如缺少必需的字段或字段格式错误。
        #返回状态码为 400，表示客户端发送了错误的请求。
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)




from django.utils import timezone
# 获取班级信息
# @cache_page(60 * 1)  # 缓存5分钟，这里覆盖了通用的缓存时长设置，按此视图函数需求缓存5分钟
@api_view(['GET'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def view_class(request):
    global CACHE_VERSION
    try:

        user_id = request.query_params.get('rootid')


        if not user_id:

            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:

            root_object = Rootone_if.objects.get(root_id=user_id)

        except Rootone_if.DoesNotExist:

            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        try:

            class_datas = Class.objects.filter(root=root_object)


            # 函数用于将 naive datetime 转换为带有时区信息的 ISO 8601 格式字符串
            def format_datetime(dt):
                if dt and timezone.is_naive(dt):
                    dt = timezone.make_aware(dt, timezone.utc)
                return dt.isoformat() if dt else None

            class_data = [
                {
                    'class_id': i.class_id,
                    'class_name': i.class_name,
                    'class_sum': i.class_sum,
                    'class_type': i.class_type,
                    'class_year': i.class_year,
                    'notes': i.notes,
                    'created_at': format_datetime(i.created_at),
                    'updated_at': format_datetime(i.updated_at),
                    'exe_person': i.root.really_name,
                    'bzr': i.bzr.rname if i.bzr else '',  # 提取班主任的名字
                    'fdy': i.fdy.rname if i.fdy else '',  # 提取辅导员的名字
                    'root': i.root.root_id,
                }
                for i in class_datas
            ]
            print('开始检查缓存键')
            cache_key = f"view_class_{CACHE_VERSION}_{request.path}_{request.GET}"
            print(f"构造的缓存键为: {cache_key}")
            cached_data = cache.get(cache_key)
            if cached_data:
                print("命中缓存，直接返回缓存数据")
                # 从缓存中取出的是之前存入的字典数据，需要重新构建Response对象返回
                return Response(cached_data, status=status.HTTP_200_OK)
            print("未命中缓存，准备设置缓存并返回最新数据")
            # 构建要存入缓存的字典数据，提取Response中的关键数据部分
            data_to_cache = {'code': 1, 'data': class_data}
            cache.set(cache_key, data_to_cache, 60 * 5)
            return Response({'code': 1, 'data': class_data}, status=status.HTTP_200_OK)
        except Exception as f:
            print(f"查询班级信息出现异常: {f}，返回400 Bad Request响应")
            return Response({'code': 2, 'message': '查询班级信息失败！'}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        print(f"服务器出现严重错误: {e}")
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

# 修改班级信息
@api_view(['PUT'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def update_class(request):
    global CACHE_VERSION
    try:
        # 获取请求参数
        class_id_q = request.data.get('class_id')
        class_name_q = request.data.get('class_name')
        class_sum_q = request.data.get('class_sum')
        class_type_q = request.data.get('class_type')
        class_year_q = request.data.get('class_year')
        notes_q = request.data.get('notes')
        bzr_q = request.data.get('bzr')
        fdy_q = request.data.get('fdy')
        user_id = request.data.get('rootid')

        # 验证超管编号
        if not user_id:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取管理员对象
        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        # 获取班级对象
        try:
            class_object = Class.objects.get(class_id=class_id_q)
        except Class.DoesNotExist:
            return Response({'code': 2, 'message': '班级不存在，请先创建'}, status=status.HTTP_404_NOT_FOUND)

        # 获取班主任和辅导员对象
        try:
            bzr_object = Teacher.objects.get(rname=bzr_q)
        except Teacher.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此班主任信息！'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            fdy_object = Teacher.objects.get(rname=fdy_q)
        except Teacher.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此辅导员信息！'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取当前超管的真实姓名
        exe_person_object = root_object

        # 实例化辅导员，创建班级与辅导员之间的联系
        with transaction.atomic():
            try:
                # 尝试获取已有的 Other_teacher_class 实例
                fdy_class = Other_teacher_class.objects.get(cclass=class_object)
                # 如果存在，则更新教师信息
                fdy_class.teacher = fdy_object
                fdy_class.save()
            except ObjectDoesNotExist:
                # 如果不存在，则创建新的 Other_teacher_class 实例
                Other_teacher_class.objects.create(
                    cclass=class_object,
                    teacher=fdy_object
                )

        # 更新班级信息
        try:
            from datetime import datetime  # 确保正确导入 datetime 类
            class_object.class_id = class_id_q
            class_object.class_name = class_name_q
            class_object.class_sum = class_sum_q
            class_object.class_type = class_type_q
            class_object.class_year = class_year_q
            class_object.notes = notes_q
            class_object.updated_at = datetime.now()
            class_object.exe_person = exe_person_object.really_name
            class_object.bzr = bzr_object
            class_object.fdy = fdy_object
            class_object.save()

            CACHE_VERSION += 1  # 每次更新班级信息后，版本号加1

            return Response({'code': 1, "message": '修改班级信息成功'}, status=status.HTTP_200_OK)
        except Exception as e:
            print(f"Error updating class: {e}")
            return Response({'code': 2, 'message': '修改班级信息失败'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)





# 添加班级功能
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def add_class(request):
    try:
        user_id = request.data.get('rootid')
        class_id_q = request.data.get('class_id')
        class_name_q = request.data.get('name')
        class_sum_q = request.data.get('studentCount')
        class_type_q = request.data.get('class_type')
        notes_q = request.data.get('notes')
        bzr_q = request.data.get('bzr')
        fdy_q = request.data.get('fdy')



        if not user_id :
            return Response({'code': 2, 'message': '操作人不允许为空！'}, status=status.HTTP_401_UNAUTHORIZED)

    #     实例化user试试
        try:
            user_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到管理员信息'}, status=status.HTTP_404_NOT_FOUND)
    #     实例化班主任和辅导员的对象
        try:
            bzr_object = Teacher.objects.get(sid=bzr_q)
        except Teacher.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到班主任信息'}, status=status.HTTP_404_NOT_FOUND)
        try:
            fdy_object = Teacher.objects.get(sid=fdy_q)
        except Teacher.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到辅导员信息'}, status=status.HTTP_404_NOT_FOUND)

        try:
            class_id_object = Class.objects.get(class_id=class_id_q.strip())
            return Response({'code': 2, 'message': '此班级id已存在，请更换其他名称。'},
                            status=status.HTTP_400_BAD_REQUEST)
        except Class.DoesNotExist:
            pass  # 如果班级名称不存在，继续执行下面的代码

        # 检查班级名称是否存在
        try:
            class_name_object = Class.objects.get(class_name=class_name_q.strip())
            return Response({'code': 2, 'message': '此班级名称已存在，请更换其他名称。'},
                            status=status.HTTP_400_BAD_REQUEST)
        except Class.DoesNotExist:
            pass  # 如果班级名称不存在，继续执行下面的代码

    #     使用get_or_create()方法来创建数据
        class_exists, yn = Class.objects.get_or_create(
            class_id=class_id_q,
            defaults={
                'class_id': class_id_q,
                'class_name': class_name_q,
                'class_sum': class_sum_q,
                'class_type': class_type_q,
                'notes': notes_q,
                'class_year': datetime.now(),
                'created_at': datetime.now(),
                'updated_at': None,
                'exe_person': user_object.really_name,
                'bzr': bzr_object,
                'fdy': fdy_object,
                'root': user_object,
            }

        )
        # 如果记录已经存在
        if yn:
            return Response({'code': 1, 'message': '班级添加成功！'}, status=status.HTTP_201_CREATED)
        else:
            return Response({'code': 2, 'message': '插入的班级信息已存在！请仔细检查后重试'},
                            status=status.HTTP_400_BAD_REQUEST)


    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)




# 删除班级
@api_view(['DELETE'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def delete_class(request):
    try:
        # 从请求体中获取 id 参数
        id = request.query_params.get('id')

        if not id:
            return Response({'code': 2, 'message': '缺少班级ID'}, status=status.HTTP_400_BAD_REQUEST)

        # 尝试获取要删除的班级对象
        class_object = Class.objects.get(class_id=id)
        class_object.delete()  # 从数据库中删除该对象
        return Response({'code': 1, 'message': '班级删除成功！'}, status=status.HTTP_200_OK)
    except Class.DoesNotExist:
        # 如果没有找到对应的班级
        return Response({'code': 2, 'message': '未找到该班级信息'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        # 处理其他所有异常
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 查看数据库存在的课程，返回id和名字
@api_view(['GET'])
# @cache_page(60 * 5)  # 缓存5分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def view_class_course(request):  # 添加 rootid 参数
    try:
        userid_q = request.query_params.get('rootid')
        if not userid_q:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 尝试获取管理员对象
            root_object = Rootone_if.objects.get(root_id=userid_q)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        try:
            # 获取课程数据，实例化课程对应管理员id的课程对象
            course_datas = Course.objects.all()

            course_data = [
                {
                    'course_id': i.course_id,
                    'name': i.name,
                }
                for i in course_datas
            ]
            return Response({'code': 1, 'data': course_data}, status=status.HTTP_200_OK)
        except Exception as f:
            return Response({'code': 2, 'message': '查询课程信息失败！'}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 查看当前班级已分配的课程和老师
@api_view(['GET'])
# @cache_page(60 * 5)  # 缓存5分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def view_class_course_already(request):  # 添加 rootid 参数
    try:

        userid_q = request.query_params.get('rootid')
        class_q = request.query_params.get('class_id')
        if not userid_q:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 尝试获取管理员对象
            root_object = Rootone_if.objects.get(root_id=userid_q)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        try:
            #    创建班级的实例对象
            class_object = Class.objects.get(class_id=class_q)
        except Class.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此班级！'}, status=status.HTTP_404_NOT_FOUND)

        try:
            class_course_datas = CourseClassZj.objects.filter(cclass=class_object)
            class_course_data = [
                {
                    'course_id': i.course.course_id,
                    'course_name': i.course.name,
                    'teacher_id': i.teacher.sid if i.teacher else ''
                }
                for i in class_course_datas
            ]
            return JsonResponse({'code': 1, 'data': list(class_course_data)}, status=status.HTTP_200_OK)

        except Exception as f:

            return Response({'code': 2, 'message': '查询课程信息失败！'}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 为班级分配课程，修改班级课程。先删后增
@api_view(['PUT'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def update_class_course(request, class_iq_q):
    try:
        # 获取请求体中的数据
        data = request.data
        userid_q = data.get('rootid')
        course_q = data.get('course')  # 课程ID列表


        if not userid_q:
            return Response({'code': 2, 'message': '管理员账号名不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=userid_q)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '未找到此管理员！'}, status=status.HTTP_401_UNAUTHORIZED)

        try:
            # 实例化课程id对象
            class_object = Class.objects.get(class_id=class_iq_q)
        except Class.DoesNotExist:
            return Response({'code': 2, 'message': '未找到该班级'}, status=status.HTTP_404_NOT_FOUND)


        if not course_q:
            return Response({'code': 2, 'message': '一个班级至少保留一门课程'}, status=status.HTTP_400_BAD_REQUEST)

        if course_q:
            # 先删后增
            class_courses = CourseClassZj.objects.filter(cclass=class_object)
            date_class_course = [
                {
                    'course_id': i.course_id
                }
                for i in class_courses
            ]

            id_list = [item['course_id'] for item in date_class_course]
            for course_id in id_list:
                if course_id not in course_q:
                    course_object = Course.objects.get(course_id=course_id)
                    class_courses = CourseClassZj.objects.filter(course=course_object)
                    class_courses.delete()
                else:
                    pass


            # 开增， 获取最新的实例化数据对象,
            c_c_objects = CourseClassZj.objects.filter(cclass=class_object)

            date_class_course1 = [
                {
                    'course_id': i.course_id
                }
                for i in c_c_objects
            ]

            # 列表推导式推导出数据库里面的课程id合集
            id_list = [item['course_id'] for item in date_class_course1]
            # 开增
            for course_id_new in course_q:

                if course_id_new not in id_list:

                    try:
                        class_course_object = Course.objects.get(course_id=course_id_new)

                    except Course.DoesNotExist:

                        return Response({'code': 2, 'message': f'不存在课程id:{course_id_new}'})
                    CourseClassZj.objects.create(course=class_course_object, cclass=class_object)
                else:
                    pass

        return Response({'code': 1, 'message': '修改成功'}, status=status.HTTP_200_OK)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 为指定班级的指定课程分配老师
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def root_set_course_teacher(request):
    try:
        user_id = request.data.get('rootid')
        teacher_id_q = request.data.get('teacher')
        class_id_q = request.data.get('class_id')
        course_id_q = request.data.get('course_id')
        # print(f"Received rootid: {user_id}")  # 输出 rootid 以便调试

        if not user_id:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 尝试获取管理员对象
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

    #     实例化课程
        try:
            course_object = Course.objects.get(course_id=course_id_q)
        except Course.DoesNotExist:
            return Response({'code': 2, 'message': '无此课程数据'}, status=status.HTTP_404_NOT_FOUND)
        # 实例化班级
        try:
            class_object = Class.objects.get(class_id=class_id_q)
        except Course.DoesNotExist:
            return Response({'code': 2, 'message': '无此课程数据'}, status=status.HTTP_404_NOT_FOUND)

        # 实例化教师
        try:
            teacher_object = Teacher.objects.get(sid=teacher_id_q)
        except Teacher.DoesNotExist:
            return Response({'code': 2, 'message': '无此教师数据'}, status=status.HTTP_404_NOT_FOUND)



        # 判断一个班级里授课老师的课程唯一性
        try:
            # 检查此教师在此班级中是否已有课程任务
            existing_courses = CourseClassZj.objects.filter(teacher=teacher_object, cclass=class_object)

            if existing_courses.exists():
                return Response({'code': 2, 'message': '操作的班级中此教师已有课程任务'},
                                status=status.HTTP_400_BAD_REQUEST)
        except MultipleObjectsReturned as e:
                # 这里理论上不会到达，因为我们已经使用了 filter 来处理多对象返回的情况

            return Response({'code': 2, 'message': '系统错误，请联系管理员'},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        except CourseClassZj.DoesNotExist:
            # 如果没有找到任何记录，这实际上是我们期望的情况之一，因此可以忽略
            pass




        #     尝试从中间表中获取指定的数据对象
        try:
            course_class_object = CourseClassZj.objects.get(course=course_object,
                                                        cclass=class_object)
        except CourseClassZj.DoesNotExist:
            return Response({'code': 2, 'message': '该班级还没有开设此课程呦'}, status=status.HTTP_404_NOT_FOUND)

        try:
            course_class_object.teacher = teacher_object
            course_class_object.save()
            return Response({'code': 1, 'message': '分配教师成功！'}, status=status.HTTP_200_OK)
        except CourseClassZj.DoesNotExist:
            return Response({'code': 2, 'message': '分配教师失败'}, status=status.HTTP_404_NOT_FOUND)




    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 课程的相关代码
from django.utils import timezone
# @cache_page(60 * 11)  # 缓存15分钟
@api_view(['GET'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def view_course(request):
    try:
        user_id = request.query_params.get('rootid')

        if not user_id:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 尝试获取管理员对象
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        try:
            # 获取课程数据，实例化课程对应管理员id的课程对象
            course_datas = Course.objects.all()

            # 函数用于将 naive datetime 转换为带有时区信息的 ISO 8601 格式字符串
            def format_datetime(dt):
                if dt and timezone.is_naive(dt):
                    dt = timezone.make_aware(dt, timezone.utc)
                return dt.isoformat() if dt else None

            course_data = [
                {
                    'course_id': i.course_id,
                    'name': i.name,
                    'summary': i.description, #课程描述
                    'credits': i.credits, #学分
                    'academic_year': i.academic_year,
                    'status': i.status,
                    'notes': i.notes,
                    'created_at': format_datetime(i.created_at),
                    'updated_at': format_datetime(i.updated_at),
                    'operator': i.exe_person,

                }
                for i in course_datas
            ]


            return Response({'code': 1, 'data': course_data}, status=status.HTTP_200_OK)
        except Exception as f:
            print(f"Error fetching class data: {f}")  # 输出查询班级时的错误
            return Response({'code': 2, 'message': '查询课程信息失败！'}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 单独加载一门课程的教师s数据
@api_view(['GET'])
# @cache_page(60 * 6)  # 缓存6分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def view_course_teachers(request):
    try:
        course_id_q = request.query_params.get('course_id')
        if not course_id_q:
            return Response({'code': 2, 'message': '传入的课程id为空！'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            course_obiect = Course.objects.get(course_id=course_id_q)
        except Course.DoesNotExist:
            return Response({'code': 2, 'message': '传入的课程id不存在！'}, status=status.HTTP_400_BAD_REQUEST)


        try:
            course_datas = CourseTeacherZj.objects.filter(course=course_obiect)

            course_data = [
                {
                    'id': i.teacher_id

                }
                for i in course_datas
            ]

            return JsonResponse({'code': 1, 'data': course_data}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'查询失败，错误原因{str(e)}'}, status=status.HTTP_401_UNAUTHORIZED)

    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 加载可以选择的教师sid，就是查还在数据库中的教师
@api_view(['GET'])
# @cache_page(60 * 7)  # 缓存7分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def y_select_teacher(request):

    try:
        userid_q = request.query_params.get('rootid')

        if not userid_q:
            return Response({'code': 2, 'message': '管理员账号不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        try:
         root_object = Rootone_if.objects.get(root_id=userid_q)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '未找到此管理员！'}, status=status.HTTP_401_UNAUTHORIZED)

        # 只获取 sid 字段, flat保证输出的是单一值而不是元组
        teacher_sids = list(Teacher.objects.all().values_list('sid', flat=True))
        return JsonResponse({'code': 1, 'data': teacher_sids}, status=status.HTTP_200_OK)

    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 改课程信息

@api_view(['PUT'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def update_course(request, course_id_q):
    try:
        # 获取请求体中的数据
        data = request.data
        userid_q = data.get('rootid')
        name_q = data.get('name')
        description_q = data.get('summary')
        credits_q = data.get('credits')
        status_q = data.get('status')
        notes_q = data.get('notes')
        teachers_q = data.get('teachers')  # 教师ID列表


        if not userid_q:
            return Response({'code': 2, 'message': '管理员账号名不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=userid_q)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '未找到此管理员！'}, status=status.HTTP_401_UNAUTHORIZED)

        try:
            course_object = Course.objects.get(course_id=course_id_q)
        except Course.DoesNotExist:
            return Response({'code': 2, 'message': '未找到该课程'}, status=status.HTTP_404_NOT_FOUND)


        # 这里很大隐患，如果是基础信息修改成功了，但是教师分配信息没能修改成功，就会导致部分改成功其余失败
        # 后续需要使用@transaction.atomic来完善
        # 更新课程基本信息
        course_object.name = name_q
        course_object.description = description_q
        course_object.credits = credits_q
        course_object.status = status_q
        course_object.notes = notes_q
        course_object.updated_at = datetime.now()

        course_object.exe_person = root_object.really_name
        #

        if not teachers_q:
            return Response({'code': 2, 'message': '一门课程至少保留一名教师'}, status=status.HTTP_400_BAD_REQUEST)

        # 更新教师关联
        if teachers_q:
            # 先删后增
            teacher_courses = CourseTeacherZj.objects.filter(course_id=course_id_q)
            date_teacher_course = [
                {
                    'teacher_id': i.teacher_id
                }
                for i in teacher_courses
            ]

            id_list = [item['teacher_id'] for item in date_teacher_course]
            # 开删
            for teacher_id in id_list:
                if teacher_id not in teachers_q:
                    teacher_object = Teacher.objects.get(sid=teacher_id)
                    teacher_courses = CourseTeacherZj.objects.filter(teacher=teacher_object)
                    teacher_courses.delete()
                else:
                    pass


            # 开增， 获取最新的实例化数据对象
            t_c_objects = CourseTeacherZj.objects.filter(course_id=course_id_q)

            date_teacher_course1 = [
                {
                    'teacher_id': i.teacher_id
                }
                for i in t_c_objects
            ]
            # # 列表推导式推导出传进来的教师id合集
            # add_teacher_id_list = [item['id'] for item in teachers_q]
            # 列表推导式推导出数据库里面的教师id合集
            id_list = [item['teacher_id'] for item in date_teacher_course1]
            # 开增
            for teacher_id_new in teachers_q:

                if teacher_id_new not in id_list:

                    try:
                        teacher_object = Teacher.objects.get(sid=teacher_id_new)

                    except Teacher.DoesNotExist:

                        return Response({'code': 2, 'message': f'不存在教师id:{teacher_id_new}'})
                    CourseTeacherZj.objects.create(course=course_object, teacher=teacher_object)
                else:
                    pass

        course_object.save()

        return Response({'code': 1, 'message': '修改成功'}, status=status.HTTP_200_OK)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 删除课程操作
@api_view(['DELETE'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def delete_course(request, course_id_q):
    try:
        user_id = request.data.get('rootid')
        if not user_id:
            return Response({'code': 2, 'message': '管理员不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            root_object = Rootone_if.objects.get(root_id=user_id)

        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此管理员'}, status=status.HTTP_404_NOT_FOUND)
        # 尝试实例化对应的课程id
        try:
            course_object = Course.objects.get(course_id=course_id_q)
        except Course.DoesNotExist:
            return Response({'code':2, 'message': '无此课程id， 请检查数据库'}, status=status.HTTP_404_NOT_FOUND)

        try:
            course_object.delete()
            return Response({'code': 1, 'message': '删除成功'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message':f'删除失败，原因:{str(e)}'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 添加课程操作
# @transaction.atomic标签确保了要么就全部成功，不然就都失败，失败了会回滚
# AddCourseAPIView是自定义的名称，继承APIView类，里面的方法名只能是post，get这种
class AddCourseAPIView(APIView):
    http_method_names = ['post']  # 只允许POST请求

    @transaction.atomic
    @permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
    def post(self, request):
        try:
            course_id_q = request.data.get('course_id')
            name_q = request.data.get('name')
            summary_q = request.data.get('summary')
            credits_q = request.data.get('credits')
            status_q = request.data.get('status')
            notes_q = request.data.get('notes')
            teachers = request.data.get('teachers')
            user_id = request.data.get('rootid')

            if not user_id:
                return Response({'code': 2, 'message': '管理员不能为空'}, status=status.HTTP_400_BAD_REQUEST)

            try:
                root_object = Rootone_if.objects.get(root_id=user_id)
            except Rootone_if.DoesNotExist:
                return Response({'code': 2, 'message': '不存在此管理员'}, status=status.HTTP_404_NOT_FOUND)

            # 检查课程是否已经存在
            if Course.objects.filter(course_id=course_id_q).exists():
                return Response({'code': 2, 'message': '此课程已存在！'}, status=status.HTTP_400_BAD_REQUEST)

            # 创建课程
            course_new_object = Course.objects.create(
                course_id=course_id_q,
                name=name_q,
                description=summary_q,
                credits=credits_q,
                status=status_q,
                notes=notes_q,
                created_at=datetime.now(),
                updated_at=datetime.now(),
                exe_person=root_object.really_name,
                root=root_object
            )

            teacher_data = [item['id'] for item in teachers]

            # 添加执教老师
            for teacherid in teacher_data:
                try:
                    teacher_object = Teacher.objects.get(sid=teacherid)
                    CourseTeacherZj.objects.create(teacher=teacher_object, course=course_new_object)
                except Teacher.DoesNotExist:
                    # 如果教师不存在，回滚整个事务
                    transaction.set_rollback(True)
                    return Response({'code': 2, 'message': '传递进来的教师id有误，数据库不存在此id'}, status=status.HTTP_404_NOT_FOUND)

            return Response({'code': 1, 'message': '创建对应课程执教老师成功'}, status=status.HTTP_200_OK)

        except Exception as e:
            # 记录详细错误信息
            print(f"An error occurred: {str(e)}")
            return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)





# 管理员查看学生奖章信息功能
@api_view(['GET'])
# @cache_page(60 * 13)  # 缓存13分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def root_view_student_award(request):

    try:
        user_id = request.query_params.get('rootid')


        if not user_id:
            return Response({'code': 2, 'message': '管理员不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此管理员'}, status=status.HTTP_404_NOT_FOUND)

    #     实例化此管理员管理的奖项对象
        try:
            award_datas = S_award.objects.filter(root=root_object)

            award_student_data = [
                {
                    'medal_id': i.award_id,
                    'name': i.award_name,
                    'awarded_by': i.award_unit,
                    'award_date': i.award_time,
                    'description': i.award_text,
                    'recipient': i.award_level,
                    'updated_at': i.updated_at,
                    'operator': root_object.really_name,
                }
                for i in award_datas
            ]

            return Response({'code': 1, 'date': list(award_student_data)}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'查询超管id:{str(user_id)}所管理的奖章信息失败,错误原因{str(e)}'},
                            status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        # 记录详细错误信息
        print(f"An error occurred: {str(e)}")
        return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 管理员查看教师奖章信息功能
# @cache_page(60 * 16)  # 缓存16分钟
@api_view(['GET'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def root_view_teacher_award(request):

    try:
        user_id = request.query_params.get('rootid')


        if not user_id:
            return Response({'code': 2, 'message': '管理员不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此管理员'}, status=status.HTTP_404_NOT_FOUND)

    #     实例化此管理员管理的奖项对象
        try:
            award_datas = T_award.objects.filter(root=root_object)

            award_teacher_data = [
                {
                    'medal_id': i.award_id,
                    'name': i.award_name,
                    'awarded_by': i.award_unit,
                    'award_date': i.award_time,
                    'description': i.award_text,
                    'recipient': i.award_level,
                    'updated_at': i.updated_at,
                    'operator': root_object.really_name,
                }
                for i in award_datas
            ]

            return Response({'code': 1, 'date': list(award_teacher_data)}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'查询超管id:{str(user_id)}所管理的奖章信息失败,错误原因{str(e)}'},
                            status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        # 记录详细错误信息
        print(f"An error occurred: {str(e)}")
        return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


from dateutil import parser
# 修改指定学生奖章信息
@api_view(['PUT'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def updata_student_award(request):
    try:
        medal_id_q = request.data.get('medal_id')
        award_name_q = request.data.get('name')
        awarded_by_q = request.data.get('awarded_by')
        award_date_q = request.data.get('award_date')
        description_q = request.data.get('description')

        user_id = request.data.get('rootid')
        print(f"Received rootid: {user_id}")  # 输出 rootid 以便调试
        if not user_id:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 尝试获取管理员对象
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        try:
            student_award_object = S_award.objects.get(award_id=medal_id_q)
        except S_award.DoesNotExist:  # 注意这里应该是S_award而不是Class
            return Response({'code': 2, 'message': '奖项不存在，请先创建'}, status=status.HTTP_404_NOT_FOUND)

        # 处理执行人，获取当前超管的真实姓名
        exe_person_object = root_object  # 已经获取过，不需要重复获取

        try:
            # 确保日期时间是带有时区信息的
            if isinstance(award_date_q, str):
                award_date_q = parser.parse(award_date_q)

            if timezone.is_naive(award_date_q):
                # 如果日期时间是naive，则使用默认时区转换为aware
                award_date_q = timezone.make_aware(award_date_q)

            student_award_object.award_name = award_name_q
            student_award_object.award_unit = awarded_by_q
            student_award_object.award_time = award_date_q
            student_award_object.award_text = description_q
            student_award_object.updated_at = timezone.now()  # 使用timezone.now()以确保带有时区信息
            student_award_object.exe_person = exe_person_object.really_name
            print(timezone.now())
            student_award_object.save()
            return Response({'code': 1, "message": '修改奖项信息成功'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'修改奖项信息失败: {str(e)}'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 修改指定教师奖章信息
@api_view(['PUT'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def updata_teacher_award(request):
    try:
        medal_id_q = request.data.get('medal_id')
        award_name_q = request.data.get('name')
        awarded_by_q = request.data.get('awarded_by')
        award_date_q = request.data.get('award_date')
        description_q = request.data.get('description')

        user_id = request.data.get('rootid')
        print(f"Received rootid: {user_id}")  # 输出 rootid 以便调试
        if not user_id:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 尝试获取管理员对象
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        try:
            teacher_award_object = T_award.objects.get(award_id=medal_id_q)
        except T_award.DoesNotExist:
            return Response({'code': 2, 'message': '奖项不存在，请先创建'}, status=status.HTTP_404_NOT_FOUND)

        # 处理执行人，获取当前超管的真实姓名
        exe_person_object = root_object  # 已经获取过，不需要重复获取

        try:
            # 确保日期时间是带有时区信息的
            if isinstance(award_date_q, str):
                award_date_q = parser.parse(award_date_q)

            if timezone.is_naive(award_date_q):
                # 如果日期时间是naive，则使用默认时区转换为aware
                award_date_q = timezone.make_aware(award_date_q)

            teacher_award_object.award_name = award_name_q
            teacher_award_object.award_unit = awarded_by_q
            teacher_award_object.award_time = award_date_q
            teacher_award_object.award_text = description_q
            teacher_award_object.updated_at = timezone.now()  # 使用timezone.now()以确保带有时区信息
            teacher_award_object.exe_person = exe_person_object.really_name
            teacher_award_object.save()
            return Response({'code': 1, "message": '修改奖项信息成功'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'修改奖项信息失败: {str(e)}'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 删除指定对象的奖章数据
@api_view(['DELETE'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def delete_teacher_award(request):
    try:
        print(123)
        medal_id_q = request.data.get('medal_id')
        # award_name_q = request.data.get('name')
        recipient_q = request.data.get('recipient')
        print(recipient_q)
        user_id = request.data.get('rootid')
        print(f"Received rootid: {user_id}")  # 输出 rootid 以便调试
        if not user_id:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 尝试获取管理员对象
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        if recipient_q == '学生':
            # 实例化对应管理员管理的学生奖项
            student_award = S_award.objects.get(award_id=medal_id_q)
            student_award.delete()
            return Response({'code': 1, 'message': '删除成功'}, status= status.HTTP_200_OK)
        elif recipient_q =='老师':
            # 实例化对应管理员管理的教师奖项
            teacher_award = T_award.objects.get(award_id=medal_id_q)
            print(teacher_award)
            teacher_award.delete()
            return Response({'code': 1, 'message': '删除成功'}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 2, 'message': '需要删除的对象类别错误，请检查'}, status=status.HTTP_400_BAD_REQUEST)
    #

    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 根据请求类型来创建对应的奖项信息
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def create_award(request):
    try:
        # 获取请求数据
        award_id_q = request.data.get('medal_id')
        award_name_q = request.data.get('award_name')
        award_unit_q = request.data.get('award_unit')
        award_time_q = request.data.get('award_time')
        award_text_q = request.data.get('award_text')
        recipient_q = request.data.get('recipient')  # 更改为更通用的名称
        print(recipient_q)
        user_id = request.data.get('rootid')

        print(f"Received rootid: {user_id}")  # 输出 rootid 以便调试
        if not user_id:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 尝试获取管理员对象
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        # 确保 recipient_q 是整数类型
        try:
            recipient_q = int(recipient_q)
        except ValueError:
            return Response({'code': 2, 'message': '授予对象必须是数字'}, status=status.HTTP_400_BAD_REQUEST)

        # 根据 recipient_q 创建奖项信息
        created = False
        message = ''
        if recipient_q == 1:
            try:

                S_award.objects.create(
                    award_id=award_id_q,
                    award_name=award_name_q,
                    award_unit=award_unit_q,
                    award_time=award_time_q,
                    award_text=award_text_q,
                    award_level=recipient_q,
                    root=root_object,
                    created_at=datetime.now(),
                    updated_at=datetime.now(),
                    exe_person=root_object.really_name
                )

                created = True
                message = '创建学生奖项信息成功'
            except Exception as e:
                message = '创建学生奖项失败'
        elif recipient_q == 2:
            try:
                T_award.objects.create(
                    award_id=award_id_q,
                    award_name=award_name_q,
                    award_unit=award_unit_q,
                    award_time=award_time_q,
                    award_text=award_text_q,
                    award_level=recipient_q,
                    root=root_object,
                    created_at=datetime.now(),
                    updated_at=datetime.now(),
                    exe_person=root_object.really_name
                )
                created = True
                message = '创建教师奖项信息成功'
            except Exception as e:
                message = '创建教师奖项失败'
        else:
            message = '需要创建的对象类别错误，请检查'

        # 返回响应
        if created:
            return Response({'code': 1, 'message': message}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 2, 'message': message}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        print(f"Server error: {e}")  # 输出服务器错误信息
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)




# 管理员查看教师奖章，返回id和name
@api_view(['GET'])
# @cache_page(60 * 3)  # 缓存3分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def get_all_the_award(request):
    try:
        root_id = request.query_params.get('rootid')

        if not root_id:
            return Response({'code': 2, 'message': '教师编号不能为空'})

        try:
            root_object = Rootone_if.objects.get(root_id=root_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到该管理员编号'}, status=status.HTTP_404_NOT_FOUND)

        try:
            award_date = T_award.objects.all().values(
                'award_id',
                'award_name'
            )

            return JsonResponse({'code': 1, 'data': list(award_date)}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'获取全部奖项信息错误，错误原因：{str(e)}'}, status=status.HTTP_400_BAD_REQUEST)


    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

# 超管为教师设置奖项
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def root_create_teacher_award(request):
    try:
        root_id = request.data.get('rootid')
        teachers = request.data.get('teachers')
        award_id_q = request.data.get('award_id')

        new_teachers = teachers[0].split(',')
        if not root_id:
            return Response({'code': 2, 'message': '超管编号不能为空'})

        try:
            root_object = Rootone_if.objects.get(root_id=root_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到该超管编号'}, status=status.HTTP_404_NOT_FOUND)
    #     实例化奖项对象

        try:
            award_object = T_award.objects.get(award_id=award_id_q)
        except T_award.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此奖项，请检查数据库'}, status=status.HTTP_404_NOT_FOUND)
    #     创建教师和奖项的中间表关系

        for teacher in new_teachers:
            try:
                # 先实例化传递进来的教师编号
                try:
                    teacher_object = Teacher.objects.get(sid=teacher)
                except Teacher.DoesNotExist:
                    return Response({'code': 2, 'message': f'不存在教师编号{str(teacher)}'},
                                    status=status.HTTP_404_NOT_FOUND)
                object = teacher_award_zj.objects.create(teacher_name=teacher_object, teacher_award=award_object)
                object.save()
                return Response({'code': 1, 'message': f'教师:{str(teacher)}奖项分配成功'}, status=status.HTTP_200_OK)

            except Exception as e:
                return Response({'code': 2, 'message': '创建教师奖章中间信息失败'}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



@api_view(['GET'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def root_head_name(request):
    try:
        # 获取请求参数
        root_id = request.query_params.get('rootid')

        if not root_id:
            return Response({'message': '管理员编号异常！'}, status=status.HTTP_400_BAD_REQUEST)

        # 查询用户信息
        try:
            user_name = Rootone_if.objects.get(root_id=root_id)
            really_name = user_name.really_name
            print(really_name)
            return Response({'name': really_name}, status=status.HTTP_200_OK)
        except ObjectDoesNotExist:
            return Response({'message': '学号不存在！'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        # 捕获其他未知错误
        return Response({'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 修改管理员个人信息
@api_view(['PUT'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def update_rootone_person(request):
    try:
        # 获取前端传来的数据
        root_id_q = request.data.get('rootid')
        name_q = request.data.get('username')
        rname_q = request.data.get('really_name')
        sex_q = request.data.get('sex')
        phone_q = request.data.get('phone')
        email_q = request.data.get('email')

        # 查找管理员信息
        try:
            user = Rootone_if.objects.get(root_id=root_id_q)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到您的信息'}, status=status.HTTP_404_NOT_FOUND)

        # 更新管理员信息
        try:
            user.username = name_q
            user.really_name = rname_q
            user.sex = sex_q
            user.phone = phone_q
            user.mailbox = email_q
            user.save()

            return Response({'code': 1, 'message': '修改成功！'}, status=status.HTTP_200_OK)
        except Exception as e:

            return Response({'code': 2, 'message': f'修改失败：{str(e)}'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 加载管理员的基础信息
@api_view(['GET'])
# @cache_page(60 * 21)  # 缓存21分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def root_all_if(request):
    try:
        root_id_q = request.query_params.get('rootid')

        if not root_id_q:
            return Response({'code': 2, 'message': '超管编号不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = Rootone_if.objects.get(root_id=root_id_q)

        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到您的信息'}, status=status.HTTP_404_NOT_FOUND)
        try:
            user_allif = Rootone_if.objects.filter(root_id=root_id_q)
            all_if = user_allif.all().values()
            return JsonResponse({'code': 1, 'data': list(all_if)}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({"code": 2, 'message': f'无法查询您的个人信息，错误原因{str(e)}'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['PUT'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def update_root_password(request):
    try:
        # 获取前端传来的数据
        rootid_q = request.data.get('rootid')
        password_q = request.data.get('newPassword')
        old_pwd_q = request.data.get('oldPassword')

        if not all([rootid_q, password_q, old_pwd_q]):
            return Response({'code': 2, 'message': '缺少必要参数'}, status=status.HTTP_400_BAD_REQUEST)

        # 查找超管信息
        try:
            user = Rootone_if.objects.get(root_id=rootid_q)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到您的信息'}, status=status.HTTP_404_NOT_FOUND)

        # 查找关联的自定义用户信息
        try:
            user_object = CustomUser.objects.get(root_info=user)
        except CustomUser.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到您的信息'}, status=status.HTTP_404_NOT_FOUND)

        # 验证旧密码
        # check_password 是 Django 内置的用于验证密码的方法，它接受两个参数：
        # password：这是用户提供的明文密码（即未加密的原始密码）。
        # encoded：这是存储在数据库中的已哈希和编码后的密码字符串。
        if not check_password(old_pwd_q, user_object.password):
            return Response({'code': 2, 'message': '旧密码错误'}, status=status.HTTP_400_BAD_REQUEST)

        # 设置新密码并保存
        try:
            user_object.password = make_password(password_q)  # 对新密码进行哈希处理
            user_object.save()
            return Response({'code': 1, 'message': '修改成功！'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'修改失败：{str(e)}'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 为指定班级分配课程表
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
@transaction.atomic  # 确保所有数据库操作在一个事务中进行
def assign_courses(request):
    try:
        course_list = request.data.get('course_list', [])
        root_id = request.data.get('rootid')
        class_id = request.data.get('classid')

        if not course_list or not class_id:
            return Response({'code': 2, 'message': '缺少必要参数'}, status=status.HTTP_400_BAD_REQUEST)

        # 实例化班级
        try:
            class_object = Class.objects.get(class_id=class_id)
        except Class.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此班级'}, status=status.HTTP_400_BAD_REQUEST)

        errors = []
        success_courses = []

        for course_data in course_list:
            week_days = course_data.get('weekDays')
            time_slots = course_data.get('timeSlots')
            location_id = course_data.get('location_id')
            course_id = course_data.get('course_id')

            if not all([week_days, time_slots, location_id, course_id]):
                errors.append(f'课程 {course_id} 分配失败: 缺少必要信息')
                continue

            # 实例化地点信息和课程
            try:
                location_object = Location.objects.get(location_id=location_id)
                course_object = Course.objects.get(course_id=course_id)
            except (Location.DoesNotExist, Course.DoesNotExist) as e:
                errors.append(f'课程 {course_id} 分配失败: {str(e)}')
                continue

            # 检查时间段是否已被占用
            existing_course = CourseClassZj.objects.filter(
                day_of_week=week_days,
                period=time_slots,
                location=location_object
            ).first()

            if existing_course and existing_course.cclass.class_id != class_id:
                errors.append(f'在 {week_days}, {time_slots},地点： {location_object.name} 已存在其他班级课程')
                continue
            # 获取指定课程指定班级的教师id并检查同一时间老师的唯一性
            teacher_object = CourseClassZj.objects.filter(
                cclass=class_object,
                course=course_object
            ).first()

            if teacher_object:
                teacher_exists = CourseClassZj.objects.filter(
                    teacher=teacher_object.teacher,
                    day_of_week=week_days,
                    period=time_slots
                ).exists()

                if teacher_exists:
                    errors.append(f'教师 {teacher_object.teacher_id} 在 {week_days}, {time_slots} 已有课程安排')
                    continue

            try:
                ass_object = CourseClassZj.objects.get(cclass=class_object,
                                                       course=course_object
                                                       )
                ass_object.day_of_week = str(week_days)
                ass_object.period = str(time_slots)
                ass_object.location = location_object
                ass_object.update_tiem = datetime.now()
                ass_object.save()
                success_courses.append(course_id)

                # 获取具有指定条件的对象列表，并按 update_time 排序，取最新的一个
                kcap_obj = CourseClassZj.objects.filter(
                    cclass=class_object,
                    day_of_week=week_days,
                    period=time_slots,
                #     使用倒叙排列取第一个，就是最新的数据
                ).order_by('-update_tiem').first()

                if kcap_obj:
                    latest_entry_id = kcap_obj.id
                    # print(f"最新的ID是: {latest_entry_id}, 时间为: {kcap_obj.update_tiem}")

                    # 修改其他所有对象的星期和节次为 None，保留最新的一个
                    updated_count = CourseClassZj.objects.filter(
                        cclass=class_object,
                    ).exclude(id=latest_entry_id).update(day_of_week=None, period=None)

            except ObjectDoesNotExist:
                return Response({"code": 2, 'message': '修改课程分配失败'}, status=status.HTTP_400_BAD_REQUEST)
        if errors:
            response_data = {
                'code': 2,
                'message': '部分课程分配失败',
                'errors': errors,
                'success_courses': success_courses
            }

            return Response(response_data, status=status.HTTP_207_MULTI_STATUS)
        else:
            return Response({
                'code': 1,
                'message': '所有课程分配成功',
                'success_courses': success_courses
            }, status=status.HTTP_200_OK)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)




# 返回超级管理员负责的班级
@api_view(['GET'])
# @cache_page(60 * 30)  # 缓存30分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def root_view_my_class(request):
    try:

        root_id = request.query_params.get('rootid')
        if not root_id:
            return Response({'code': 2, 'message': '超管编号不能为空'})

        try:
            root_object = Rootone_if.objects.get(root_id=root_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到该管理员编号'}, status=status.HTTP_404_NOT_FOUND)

        try:
    #         实例化班级对象合集
            class_objects_date = Class.objects.filter(root=root_object)
        except Class.DoesNotExist:
            return Response({'code': 2, 'message': f'实例化管理员id{str(root_id)}关联的班级失败'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            class_date = [
                {'class_id': i.class_id,
                 'class_name': i.class_name
                }
                for i in class_objects_date
            ]

            return JsonResponse({'code': 1, 'data': list(class_date)}, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({'code': 2, 'message': '获取班级列表失败'}, status=status.HTTP_400_BAD_REQUEST)


    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 返回指定班级的课程信息，（通用）
@api_view(['GET'])
# @cache_page(60 * 35)  # 缓存35分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def view_C_S(request):
    try:
        # 获取查询参数
        root_id = request.query_params.get('rootid')
        student_id = request.query_params.get('studentid')
        teacher_id = request.query_params.get('teacherid')
        class_id = request.query_params.get('classid')

        # 检查是否有两个或以上的ID存在
        if sum(bool(x) for x in [root_id, student_id, teacher_id]) > 1:
            return Response({"code": 2, 'message': '无效的请求'}, status=status.HTTP_400_BAD_REQUEST)

        # 根据提供的ID类型执行相应的操作
        if root_id:
            try:
                root_object = Rootone_if.objects.get(root_id=root_id)
                if not class_id:
                    return Response({"code": 2, 'message': '缺少班级ID'}, status=status.HTTP_400_BAD_REQUEST)
                class_object = Class.objects.get(class_id=class_id)

                kc_datas = CourseClassZj.objects.filter(cclass=class_object)

                # 构建kc_data列表时，使用getattr确保安全访问属性
                kc_data = [
                    {
                        'course_id': getattr(i.course, 'course_id', ''),
                        'location_id': getattr(i.location, 'location_id', '') if i.location else '',
                        'weekDays': str(getattr(i, 'day_of_week', '')),
                        'timeSlots': str(getattr(i, 'period', '')),
                    }
                    for i in kc_datas
                ]

                return Response({'code': 1, 'data': kc_data}, status=status.HTTP_200_OK)
            except ObjectDoesNotExist as e:
                return Response({'code': 2, 'message': '不存在管理员或班级信息'}, status=status.HTTP_404_NOT_FOUND)


        elif student_id:

            try:

                student_object = SStudents.objects.get(student_id=student_id)
                class_object_s = student_object.of_class
                kc_datas = CourseClassZj.objects.filter(cclass=class_object_s)

                kc_data = [
                    {

                        'course_name': getattr(i.course, 'course_name', ''),  # 使用 course_id 保持一致性
                        'location_name': getattr(i.location, 'name', '') if i.location else '',
                        'weekDay': str(getattr(i, 'day_of_week', '')) ,
                        'timeSlot': str(getattr(i, 'period', '')) ,
                        'teacher_name': getattr(i.teacher, 'rname', '') if i.teacher else ''
                    }
                    for i in kc_datas
                ]

                return Response({'code': 1, 'data': kc_data}, status=status.HTTP_200_OK)
            except ObjectDoesNotExist as e:
                return Response({'code': 2, 'message': '不存在学生或班级信息'}, status=status.HTTP_404_NOT_FOUND)

        elif teacher_id:
            try:
                teacher_object = Teacher.objects.get(sid=teacher_id)
                kc_datas = CourseClassZj.objects.filter(teacher=teacher_object)
                kc_data = [
                    {
                        'course_id': getattr(i.course, 'course_id', ''),  # 使用 course_id 保持一致性
                        'location_name': getattr(i.location, 'name', '') if i.location else '',
                        'weekDay': str(getattr(i, 'day_of_week', '')),
                        'timeSlot': int(getattr(i, 'period', 0)),
                        'class_name': getattr(i.cclass, 'class_name', '')
                    }
                    for i in kc_datas
                ]

                return Response({'code': 1, 'data': kc_data}, status=status.HTTP_200_OK)
            except ObjectDoesNotExist as e:
                return Response({'code': 2, 'message': '不存在教师信息'}, status=status.HTTP_404_NOT_FOUND)


        else:
            return Response({"code": 2, 'message': '无效的请求'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 下面是对教师信息的增删查改和批量删除，导入导出


# 获取所有教师信息
@api_view(['GET'])
# @cache_page(60 * 18)  # 缓存15分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def get_all_teachers(request):
    """获取所有教师信息"""

    try:
        userid_q = request.query_params.get('rootid')
        if not userid_q:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 尝试获取管理员对象
            root_object = Rootone_if.objects.get(root_id=userid_q)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        obj_teachers = Teacher.objects.all().values()

        teachers = list(obj_teachers)
        return JsonResponse({'code': 1, 'data': teachers}, status=status.HTTP_200_OK)
    except Exception as e:
        return JsonResponse({'code': 0, 'data': "捕获教师信息出现异常"+str(e)})


@api_view(['GET'])
# @cache_page(60 * 19)  # 缓存19分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def query_teachers(request):
    """查询教师信息"""
    try:
        userid_q = request.query_params.get('rootid')
        input_str = request.query_params.get('inputstr', '').strip()

        print(userid_q)
        print(input_str)
        if not userid_q:
            return Response({'code': 2, 'message': '超管编号为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 尝试获取管理员对象
            root_object = Rootone_if.objects.get(root_id=userid_q)
        except Rootone_if.DoesNotExist:
            return Response({'code': 2, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        if not input_str:
            return JsonResponse({'code': 0, 'msg': "查询条件不能为空"}, status=status.HTTP_400_BAD_REQUEST)

        # 构建查询条件
        query_conditions = (
                Q(sid__icontains=input_str) |
                Q(name__icontains=input_str) |
                Q(sex__icontains=input_str) |
                Q(rname__icontains=input_str) |
                Q(level__icontains=input_str) |
                Q(phone__icontains=input_str) |
                Q(origin__icontains=input_str) |
                Q(mailbox__icontains=input_str) |
                Q(by_school__icontains=input_str) |
                Q(major__icontains=input_str) |
                Q(school_encode__icontains=input_str) |
                Q(degree__icontains=input_str) |
                Q(posts_name__icontains=input_str) |
                Q(posts_id__icontains=input_str) |
                Q(org__icontains=input_str) |
                Q(intro__icontains=input_str) |
                Q(f_name__icontains=input_str) |
                Q(f_phone__icontains=input_str) |
                Q(m_name__icontains=input_str) |
                Q(m_phone__icontains=input_str) |
                Q(address__icontains=input_str) |
                Q(state__icontains=input_str)  #新增状态查询
        )


        # 使用 ORM 获取满足条件的教师信息，并把对象转为字典格式
        teachers = list(Teacher.objects.filter(query_conditions).values())
        # 返回结果
        return JsonResponse({'code': 1, 'data': teachers})
    except Exception as e:
        # 捕获所有其他异常并返回服务器错误响应
        return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
# @cache_page(60 * 2)  # 缓存2分钟
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def is_exsits_teacherid(request):

    """判断教师编号是否存在"""
    #接收传递过来的学号
    teacher_id = request.query_params.get('sid')
    try:
        obj_teachers = Teacher.objects.filter(sid=teacher_id)
        if obj_teachers.count() == 0:
            #设置返回的参数，1表示请求成功且不存在该学号
            return JsonResponse({'code': 1, 'exists': False})
        else:
            return JsonResponse({'code': 1, 'exists': True})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "校验教师编号失败，具体原因: "+ str(e)})





@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def add_teacher(request):
    """添加教师到数据库"""
    try:
        # 获取前端传递过来的数据
        data = request.data
        # 校验 rootid 是否存在且有效
        rootid = data.get('rootid')
        if not rootid:
            return Response({'code': 0, 'message': '缺少必填字段: rootid'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=rootid)
        except Rootone_if.DoesNotExist:
            return Response({'code': 0, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        # 定义必填字段列表
        required_fields = ['sid', 'rname', 'sex', 'phone', 'origin']

        # 验证必填字段是否存在并且非空
        for field in required_fields:
            if field not in data or not data[field].strip():
                return Response({'code': 0, 'message': f'缺少必填字段或为空: {field}'}, status=status.HTTP_400_BAD_REQUEST)

            # 处理可选的日期字段，将空字符串转换为 None

        def parse_date(date_str):
            if date_str and date_str.strip():
                try:
                    return datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
                except ValueError:
                    raise ValidationError({'message': '日期格式不正确'})
            return None

        birthday = parse_date(data.get('birthday'))
        hire = parse_date(data.get('hire'))

        # 使用事务保证原子性
        with transaction.atomic():
            # 创建 Teacher 对象并赋值
            obj_teacher = Teacher(
                sid=data.get('sid'),
                rname=data.get('rname'),
                sex=data.get('sex'),
                phone=data.get('phone'),
                origin=data.get('origin'),
                birthday=birthday,
                mailbox=data.get('mailbox'),
                by_school=data.get('by_school'),
                major=data.get('major'),
                school_encode=data.get('school_encode'),
                hire=hire,
                degree=data.get('degree'),
                posts_name=data.get('posts_name'),
                posts_id=data.get('posts_id'),
                org=data.get('org'),
                intro=data.get('intro'),
                f_name=data.get('f_name'),
                f_phone=data.get('f_phone'),
                m_name=data.get('m_name'),
                m_phone=data.get('m_phone'),
                address=data.get('address'),
                state = data.get('state'),

            )

            # 执行保存操作
            obj_teacher.save()


            # 保存教师信息后为其创建账号
            teacher_obj = Teacher.objects.filter(student_id=data.get('sid')).first()

            # 创建账号
            CustomUser.objects.create(
                identifier=data.get('sid'),
                user_type='teacher',
                password=make_password(str(data.get('sid'))),
                teacher_info=teacher_obj
            )

            # 使用ORM获取所有教师信息，并把对象转为字典格式
            obj_teachers = Teacher.objects.all().values()
            # 把外层容器转为List
            teacher = list(obj_teachers)
            # 返回
            return JsonResponse({'code': 1, 'data': teacher})

        # 返回成功信息
        return Response({'code': 1, 'message': '教师信息添加成功'}, status=status.HTTP_200_OK)

    except Exception as e:
        # 捕获所有其他异常并返回服务器错误响应
        print(f"Unexpected error: {e}")  # 调试信息
        return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


import datetime  # 确保正确导入 datetime 模块
@api_view(['PUT'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def update_teacher(request):
    """修改教师到数据库"""
    try:
        # 获取前端传递过来的数据
        data = request.data

        # 校验 rootid 是否存在且有效
        user_id = data.get('rootid')
        if not user_id:
            return Response({'code': 0, 'message': '缺少管理员认证编号'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 0, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        # 查找要修改的教师信息
        sno = data.get('sid')
        if not sno:
            return Response({'code': 0, 'message': '缺少必填字段: sid'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            obj_teacher = Teacher.objects.get(sid=sno)  # 使用 sid 字段查找教师
        except Teacher.DoesNotExist:
            return Response({'code': 0, 'message': '找不到指定的教师'}, status=status.HTTP_404_NOT_FOUND)

        # 处理可选的日期字段，将空字符串转换为 None
        def parse_date(date_str):
            if date_str and date_str.strip():
                try:
                    return datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
                except ValueError:
                    raise ValidationError({'message': '日期格式不正确'})
            return None

        birthday = parse_date(data.get('birthday'))
        hire = parse_date(data.get('hire'))

        # 使用事务保证原子性
        with transaction.atomic():
            # 构建 Teacher 对象的参数字典，并过滤掉值为 None 或空字符串的键值对
            teacher_data = {
                key: (parse_date(value) if key in ['birthday', 'hire'] else value)
                for key, value in data.items()
                if hasattr(Teacher, key) and (value is not None and value != '')
            }

            # 更新 Teacher 对象的属性
            for key, value in teacher_data.items():
                setattr(obj_teacher, key, value)

            # 执行保存操作
            obj_teacher.save()


            # 使用ORM获取所有教师信息，并把对象转为字典格式
            obj_teachers = Teacher.objects.all().values()
            # 把外层容器转为List
            teacher = list(obj_teachers)
            # 返回
            return JsonResponse({'code': 1, 'data': teacher})

        # 返回成功信息
        return Response({'code': 1, 'message': '教师信息更新成功'}, status=status.HTTP_200_OK)

    except Exception as e:
        # 捕获所有其他异常并返回服务器错误响应
        print(f"Unexpected error: {e}")  # 调试信息
        return Response({'code': 0, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['DELETE'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def delete_teacher(request):
    """删除一条教师数据"""
    # 接收前端传递过来的值

    try:

        data = request.data
        # 查找到要修改的教师信息
        # 校验 rootid 是否存在且有效
        user_id = data.get('rootid')
        if not user_id:
            return Response({'code': 0, 'message': '缺少管理员认证编号'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 0, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)

        obj_teacher = Teacher.objects.get(sid=data.get('sid'))
        # 执行删除
        obj_teacher.delete()

        # 使用ORM获取所有教师信息，并把对象转为字典格式
        obj_teachers = Teacher.objects.all().values()
        # 把外层容器转为List
        teacher = list(obj_teachers)
        # 返回
        return JsonResponse({'code': 1, 'data': teacher})

    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "删除教师信息写入数据库出现异常：具体原因-" + str(e)})

@api_view(['DELETE'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def delete_teachers(request):
    """批量删除教师信息"""

    try:
        data = request.data
        # 校验 rootid 是否存在且有效
        user_id = data.get('rootid')
        if not user_id:
            return Response({'code': 0, 'message': '缺少管理员认证编号'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            root_object = Rootone_if.objects.get(root_id=user_id)
        except Rootone_if.DoesNotExist:
            return Response({'code': 0, 'message': '不存在此编码对象'}, status=status.HTTP_404_NOT_FOUND)
        # 遍历传递的集合，并确保 teacher 是一个列表
        teachers_to_delete = data.get('teacher', [])
        if not isinstance(teachers_to_delete, list):
            return Response({'code': 0, 'message': '无效的教师编号列表'}, status=status.HTTP_400_BAD_REQUEST)
        # 使用事务保证原子性
        with transaction.atomic():
            # 执行删除操作
            Teacher.objects.filter(sid__in=[t['sid'] for t in teachers_to_delete]).delete()

            # 使用ORM获取所有教师信息，并把对象转为字典格式
            obj_teachers = Teacher.objects.all().values()
            # 把外层容器转为List
            teacher = list(obj_teachers)
            # 返回
            return JsonResponse({'code': 1, 'data': teacher})

            return Response({'code': 1, 'message': '批量删除成功'}, status=status.HTTP_200_OK)
    except Exception as e:
        # 捕获所有其他异常并返回服务器错误响应
        print(f"Unexpected error: {e}")  # 调试信息
        return Response({'code': 0, 'msg': "批量删除教师信息出现异常：具体原因-" + str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)